import React, { useState, useEffect } from 'react';
import {
  Box,
  Typography,
  Button,
  Dialog,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Tooltip,
  Tabs,
  Tab,
} from '@mui/material';
import AddIcon from '@mui/icons-material/Add';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import CalculateIcon from '@mui/icons-material/Calculate';
import { Product, TimeLabel } from '../../types/product';
import { 
  getAllProducts, 
  getAllReverseCalculations,
  saveReverseCalculation,
  deleteReverseCalculation,
  ReverseCalculation,
  InvestmentPlan,
  getAllInvestmentPlans,
  saveInvestmentPlan,
  deleteInvestmentPlan
} from '../../services/storage';
import InvestmentForm from '../../components/InvestmentForm';
import ReverseCalculationForm from '../../components/ReverseCalculationForm';
import PerformanceAnalysis from '../../components/PerformanceAnalysis';
import { CalculationResult, RateInfo, InvestmentDetail } from '../../types/calculation';

interface InvestmentFormData {
  productId: string;
  principal: number;
  startDate: Date;
  endDate: Date;
  id?: string;  // 添加可选的ID字段用于编辑现有投资计划
}

interface TabPanelProps {
  children?: React.ReactNode;
  index: number;
  value: number;
}

const TabPanel: React.FC<TabPanelProps> = (props) => {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`calculator-tabpanel-${index}`}
      aria-labelledby={`calculator-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box sx={{ pt: 3 }}>
          {children}
        </Box>
      )}
    </div>
  );
};

const a11yProps = (index: number) => {
  return {
    id: `calculator-tab-${index}`,
    'aria-controls': `calculator-tabpanel-${index}`,
  };
};

const CalculatorPage: React.FC = () => {
  const [products, setProducts] = useState<Product[]>([]);
  const [openInvestForm, setOpenInvestForm] = useState(false);
  const [openReverseForm, setOpenReverseForm] = useState(false);
  const [calculations, setCalculations] = useState<CalculationResult[]>([]);
  const [reverseCalculations, setReverseCalculations] = useState<ReverseCalculation[]>([]);
  const [editingReverse, setEditingReverse] = useState<ReverseCalculation | null>(null);
  const [editingInvestment, setEditingInvestment] = useState<{
    investmentId: string;
    productId: string;
    principal: number;
    startDate: Date;
    endDate: Date;
  } | null>(null);
  const [tabValue, setTabValue] = useState(0);

  const handleTabChange = (event: React.SyntheticEvent, newValue: number) => {
    setTabValue(newValue);
  };

  // 在组件加载时加载所有数据
  useEffect(() => {
    loadProducts();
    loadReverseCalculations();
    loadInvestmentPlans();
  }, []);

  // 当 products 改变时重新加载投资计划
  useEffect(() => {
    if (products.length > 0) {
      loadInvestmentPlans();
    }
  }, [products]);

  const loadReverseCalculations = () => {
    try {
      const calculations = getAllReverseCalculations();
      setReverseCalculations(calculations);
    } catch (error) {
      console.error('加载收益反算记录失败:', error);
    }
  };

  const loadInvestmentPlans = () => {
    try {
      const plans = getAllInvestmentPlans();
      
      if (plans.length === 0) {
        setCalculations([]);
        return;
      }
      
      // 按产品ID分组
      const plansByProduct = plans.reduce((acc, plan) => {
        if (!plan.startDate || !plan.endDate) return acc;
        
        const productId = plan.productId;
        if (!acc[productId]) {
          acc[productId] = [];
        }
        acc[productId].push(plan);
        return acc;
      }, {} as Record<string, InvestmentPlan[]>);
      
      // 为每个产品计算汇总结果
      const results: CalculationResult[] = [];
      
      for (const productId in plansByProduct) {
        const productPlans = plansByProduct[productId];
        const product = products.find(p => p.id === productId);
        
        if (!product) continue;
        
        // 计算每个投资计划的详情
        const investments: InvestmentDetail[] = [];
        let totalPrincipal = 0;
        let totalInterest = 0;
        
        // 收集所有日期标签的利率信息
        const ratesByLabel = new Map<TimeLabel, RateInfo>();
        product.historyRates.forEach(rate => {
          if (!ratesByLabel.has(rate.timeLabel)) {
            const rateValue = rate.advertisedRate || rate.rate;
            
            ratesByLabel.set(rate.timeLabel, {
              timeLabel: rate.timeLabel,
              rate: rateValue,
              dateRange: `${formatDate(new Date(rate.startDate))} - ${formatDate(new Date(rate.endDate))}`,
              interest: 0 // 初始化为0，后续累加
            });
          }
        });
        
        // 处理每个投资计划
        for (const plan of productPlans) {
          const startDate = new Date(plan.startDate);
          const endDate = new Date(plan.endDate);
          const periodDays = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
          
          // 获取适用的利率记录
          const applicableRate = product.historyRates
            .filter(rate => new Date(rate.startDate) <= startDate)
            .sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime())[0];
          
          if (!applicableRate) continue;
          
          // 计算主要预测收益
          const annualRate = applicableRate.advertisedRate || applicableRate.rate;
          const interest = (plan.principal * annualRate / 100 * periodDays) / 365;
          const interestRounded = Number(interest.toFixed(2));
          
          // 添加投资详情
          investments.push({
            id: plan.id,
            periodDays,
            investmentRange: `${formatDate(startDate)} - ${formatDate(endDate)}`,
            principal: plan.principal,
            interest: interestRounded
          });
          
          // 累计总额
          totalPrincipal += plan.principal;
          totalInterest += interestRounded;
          
          // 更新每个日期标签的预测利息
          ratesByLabel.forEach((rateInfo, label) => {
            const rateValue = rateInfo.rate;
            const rateInterest = (plan.principal * rateValue / 100 * periodDays) / 365;
            rateInfo.interest += Number(rateInterest.toFixed(2));
          });
        }
        
        // 创建产品汇总结果
        results.push({
          productId,
          productName: product.name,
          bankName: product.bank,
          rates: Array.from(ratesByLabel.values()),
          investments,
          totalPrincipal,
          totalInterest
        });
      }
      
      setCalculations(results);
    } catch (error) {
      console.error('加载投资计划失败:', error);
    }
  };
  
  // 格式化日期的辅助函数
  const formatDate = (date: Date) => date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');

  const loadProducts = () => {
    try {
      const allProducts = getAllProducts();
      setProducts(allProducts);
    } catch (error) {
      console.error('加载产品列表失败:', error);
    }
  };

  const handleAddInvestment = () => {
    setEditingInvestment(null);
    setOpenInvestForm(true);
  };
  
  const handleEditInvestment = (productId: string, investmentId: string) => {
    try {
      const plans = getAllInvestmentPlans();
      const plan = plans.find(p => p.id === investmentId);
      
      if (plan) {
        setEditingInvestment({
          investmentId: plan.id,
          productId: plan.productId,
          principal: plan.principal,
          startDate: new Date(plan.startDate),
          endDate: new Date(plan.endDate)
        });
        setOpenInvestForm(true);
      }
    } catch (error) {
      console.error('获取投资计划失败:', error);
      alert('获取投资计划失败，请重试');
    }
  };

  const handleAddReverseCalculation = () => {
    setEditingReverse(null);
    setOpenReverseForm(true);
  };

  const calculateInvestment = (plan: InvestmentFormData, shouldSave: boolean = false): CalculationResult | null => {
  const product = products.find(p => p.id === plan.productId);
  if (!product) {
    console.error('未找到产品');
    return null;
  }

  // 计算投资期间的收益
  const startDate = new Date(plan.startDate);
  const endDate = new Date(plan.endDate);
  const periodDays = Math.floor((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
  
  // 获取所有利率记录
  const formatDate = (date: Date) => date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-');

  // 获取最新的适用利率记录用于计算收益
  const applicableRate = product.historyRates
    .filter(rate => new Date(rate.startDate) <= startDate)
    .sort((a, b) => new Date(b.startDate).getTime() - new Date(a.startDate).getTime())[0];

  if (!applicableRate) {
    console.error('无法找到适用的利率');
    return null;
  }

  // 按时间标签分组整理利率信息，并为每个标签计算收益
  const ratesByLabel = new Map<TimeLabel, RateInfo>();
  product.historyRates.forEach(rate => {
    if (!ratesByLabel.has(rate.timeLabel)) {
      const rateValue = rate.advertisedRate || rate.rate;
      // 为每个日期标签计算预期收益
      const rateInterest = (plan.principal * rateValue / 100 * periodDays) / 365;
      
      ratesByLabel.set(rate.timeLabel, {
        timeLabel: rate.timeLabel,
        rate: rateValue,
        dateRange: `${formatDate(new Date(rate.startDate))} - ${formatDate(new Date(rate.endDate))}`,
        interest: Number(rateInterest.toFixed(2))
      });
    }
  });

  // 使用最新适用利率计算主要预测收益
  const annualRate = applicableRate.advertisedRate || applicableRate.rate;
  const interest = (plan.principal * annualRate / 100 * periodDays) / 365;
  
  // 创建投资详情
  const investmentDetail: InvestmentDetail = {
    id: Date.now().toString(),
    periodDays,
    investmentRange: `${formatDate(startDate)} - ${formatDate(endDate)}`,
    principal: plan.principal,
    interest: Number(interest.toFixed(2))
  };

  // 查找现有的同一产品的计算结果
  const existingResult = calculations.find(calc => calc.productId === product.id);

  if (existingResult && shouldSave) {
    // 更新现有结果
    const updatedResult: CalculationResult = {
      ...existingResult,
      investments: [...existingResult.investments, investmentDetail],
      totalPrincipal: existingResult.totalPrincipal + plan.principal,
      totalInterest: existingResult.totalInterest + Number(interest.toFixed(2))
    };

    if (shouldSave) {
      try {
        // 创建新的投资计划
        const newPlan: InvestmentPlan = {
          id: investmentDetail.id,
          productId: plan.productId,
          principal: plan.principal,
          startDate: plan.startDate,
          endDate: plan.endDate,
          createdAt: new Date()
        };
        
        // 保存到本地存储
        saveInvestmentPlan(newPlan);
        
        // 更新界面显示
        setCalculations(prev => prev.map(item => 
          item.productId === product.id ? updatedResult : item
        ));
        setOpenInvestForm(false);
      } catch (error) {
        console.error('保存投资计划失败:', error);
        alert('保存失败，请重试');
        return null;
      }
    }
    
    return updatedResult;
  } else {
    // 创建新的计算结果
    const result: CalculationResult = {
      productId: product.id,
      productName: product.name,
      bankName: product.bank,
      rates: Array.from(ratesByLabel.values()),
      investments: [investmentDetail],
      totalPrincipal: plan.principal,
      totalInterest: Number(interest.toFixed(2))
    };

    if (shouldSave) {
    try {
      // 设置投资详情的ID
      investmentDetail.id = plan.id || Date.now().toString();
      
      // 创建或更新投资计划
      const planToSave: InvestmentPlan = {
        id: investmentDetail.id,
        productId: plan.productId,
        principal: plan.principal,
        startDate: plan.startDate,
        endDate: plan.endDate,
        createdAt: new Date()
      };
      
      // 保存到本地存储
      saveInvestmentPlan(planToSave);
      
      // 如果是编辑现有计划
      if (plan.id) {
        // 更新界面显示
        setCalculations(prev => {
          // 找到包含此投资的产品结果
          let productFound = false;
          const updatedCalculations = prev.map(calc => {
            // 查找包含此投资ID的产品
            const investmentIndex = calc.investments.findIndex(inv => inv.id === plan.id);
            
            if (investmentIndex >= 0) {
              productFound = true;
              
              // 更新投资详情
              const updatedInvestments = [...calc.investments];
              updatedInvestments[investmentIndex] = investmentDetail;
              
              // 重新计算总额
              const totalPrincipal = updatedInvestments.reduce((sum, inv) => sum + inv.principal, 0);
              const totalInterest = updatedInvestments.reduce((sum, inv) => sum + inv.interest, 0);
              
              return {
                ...calc,
                investments: updatedInvestments,
                totalPrincipal,
                totalInterest
              };
            }
            return calc;
          });
          
          return updatedCalculations;
        });
      } else {
        // 添加新计划
        setCalculations(prev => [...prev, result]);
      }
      setOpenInvestForm(false);
      } catch (error) {
        console.error('保存投资计划失败:', error);
        alert('保存失败，请重试');
        return null;
      }
    }
    
    return result;
  }
};

// 删除投资计划
const handleDeleteInvestmentPlan = (result: CalculationResult, investmentId: string) => {
  if (window.confirm('确定要删除这条投资计划吗？')) {
    try {
      // 删除指定的投资计划
      deleteInvestmentPlan(investmentId);
      
      // 重新加载所有投资计划
      loadInvestmentPlans();
    } catch (error) {
      console.error('删除投资计划失败:', error);
      alert('删除失败，请重试');
    }
  }
};

  const handleReverseCalculation = (data: Omit<ReverseCalculation, 'id'>) => {
    try {
      const calculation: ReverseCalculation = editingReverse
        ? { ...data, id: editingReverse.id }
        : { ...data, id: Date.now().toString() };
      
      saveReverseCalculation(calculation);
      loadReverseCalculations();
      setOpenReverseForm(false);
      setEditingReverse(null);
    } catch (error) {
      console.error('保存收益反算记录失败:', error);
      alert('保存失败，请重试');
    }
  };

  const handleEditReverseCalculation = (calculation: ReverseCalculation) => {
    setEditingReverse(calculation);
    setOpenReverseForm(true);
  };

  const handleDeleteReverseCalculation = (id: string) => {
    if (window.confirm('确定要删除这条记录吗？')) {
      try {
        deleteReverseCalculation(id);
        loadReverseCalculations();
      } catch (error) {
        console.error('删除收益反算记录失败:', error);
        alert('删除失败，请重试');
      }
    }
  };

  const formatMoney = (amount: number): string => {
    return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
  };

  const formatRate = (rate: number): string => {
    return `${rate.toFixed(2)}%`;
  };

  return (
    <Box>
      <Box display="flex" justifyContent="space-between" alignItems="center" mb={2}>
        <Typography variant="h5">投资收益测算</Typography>
        <Box>
          <Button
            variant="outlined"
            startIcon={<CalculateIcon />}
            onClick={handleAddReverseCalculation}
            sx={{ mr: 2 }}
          >
            收益反算
          </Button>
          <Button
            variant="contained"
            startIcon={<AddIcon />}
            onClick={handleAddInvestment}
          >
            添加投资
          </Button>
        </Box>
      </Box>
      
      <Box sx={{ borderBottom: 1, borderColor: 'divider' }}>
        <Tabs value={tabValue} onChange={handleTabChange} aria-label="calculator tabs">
          <Tab label="收益预测" {...a11yProps(0)} />
          <Tab label="收益反算" {...a11yProps(1)} />
          <Tab label="数据对比分析" {...a11yProps(2)} />
        </Tabs>
      </Box>
      
      <TabPanel value={tabValue} index={0}>

      {calculations.length > 0 ? (
        <Box>
          <TableContainer component={Paper}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>产品信息</TableCell>
                  <TableCell>日期标签</TableCell>
                  <TableCell>年化收益</TableCell>
                  <TableCell align="right">计划投入本金</TableCell>
                  <TableCell>投资期限</TableCell>
                  <TableCell align="right">预测利息</TableCell>
                  <TableCell align="center">操作</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {calculations.map((result) => (
                  <React.Fragment key={result.productId}>
                    {/* 产品信息行 */}
                    <TableRow>
                      <TableCell rowSpan={result.investments.length + 2}>
                        <Box>
                          <Typography variant="body2" gutterBottom>
                            {result.bankName}
                          </Typography>
                          <Typography variant="body2" color="textSecondary">
                            {result.productName}
                          </Typography>
                        </Box>
                      </TableCell>
                      <TableCell rowSpan={result.investments.length + 2}>
                        {result.rates.map(rate => (
                          <Typography key={rate.timeLabel} variant="body2" gutterBottom>
                            {rate.timeLabel}
                          </Typography>
                        ))}
                      </TableCell>
                      <TableCell rowSpan={result.investments.length + 2}>
                        {result.rates.map(rate => (
                          <Box key={rate.timeLabel} mb={1}>
                            <Typography variant="body2" sx={{ color: 'error.main', fontWeight: 'bold' }}>
                              {formatRate(rate.rate)}
                            </Typography>
                            <Typography variant="caption" color="textSecondary" display="block">
                              {rate.dateRange}
                            </Typography>
                            <Typography variant="body2" sx={{ color: 'primary.main' }}>
                              预测利息: {formatMoney(rate.interest)}
                            </Typography>
                          </Box>
                        ))}
                      </TableCell>
                    </TableRow>
                    
                    {/* 投资明细行 */}
                    {result.investments.map((investment) => (
                      <TableRow key={investment.id}>
                        <TableCell align="right">
                          {formatMoney(investment.principal)}
                        </TableCell>
                        <TableCell>
                          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                            <Box>
                              <Typography variant="body2">
                                {investment.periodDays}天
                              </Typography>
                              <Typography variant="caption" color="textSecondary" display="block">
                                {investment.investmentRange}
                              </Typography>
                            </Box>
                            <IconButton 
                              size="small" 
                              onClick={() => handleDeleteInvestmentPlan(result, investment.id)}
                            >
                              <DeleteIcon fontSize="small" />
                            </IconButton>
                          </Box>
                        </TableCell>
                        <TableCell align="right">
                        {formatMoney(investment.interest)}
                      </TableCell>
                      <TableCell align="center">
                        <Tooltip title="编辑">
                          <IconButton
                            size="small"
                            onClick={() => handleEditInvestment(result.productId, investment.id)}
                          >
                            <EditIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="删除">
                          <IconButton
                            size="small"
                            onClick={() => handleDeleteInvestmentPlan(result, investment.id)}
                          >
                            <DeleteIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                    ))}
                    
                    {/* 合计行 */}
                    <TableRow sx={{ backgroundColor: 'action.hover' }}>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                        合计: {formatMoney(result.totalPrincipal)}
                      </TableCell>
                      <TableCell></TableCell>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                        {formatMoney(result.totalInterest)}
                      </TableCell>
                      <TableCell></TableCell>
                    </TableRow>
                  </React.Fragment>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Box>
      ) : (
        <Box textAlign="center" mt={4}>
          <Typography color="textSecondary">
            点击"添加投资"按钮开始计算收益预测
          </Typography>
        </Box>
      )}
      </TabPanel>
      
      <TabPanel value={tabValue} index={1}>
      {reverseCalculations.length > 0 ? (
        <Box>
          <TableContainer component={Paper}>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>产品信息</TableCell>
                  <TableCell>投资期限</TableCell>
                  <TableCell align="right">实际投资金额</TableCell>
                  <TableCell align="right">当前收益</TableCell>
                  <TableCell align="right">实际年化</TableCell>
                  <TableCell align="right">万份收益</TableCell>
                  <TableCell align="center">操作</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {/* 按产品分组显示反算记录 */}
                {Object.values(reverseCalculations.reduce<Record<string, ReverseCalculation[]>>((acc, calc) => {
                  const key = calc.productId;
                  if (!acc[key]) {
                    acc[key] = [];
                  }
                  acc[key].push(calc);
                  return acc;
                }, {})).map((group) => (
                  <React.Fragment key={group[0].productId}>
                    {/* 产品信息行 */}
                    <TableRow>
                      <TableCell rowSpan={group.length + 1}>
                        <Typography variant="body2" gutterBottom>
                          {group[0].bankName}
                        </Typography>
                        <Typography variant="body2" color="textSecondary">
                          {group[0].productName}
                        </Typography>
                      </TableCell>
                      {/* 第一条记录 */}
                      <TableCell>
                        {`${new Date(group[0].startDate).toLocaleDateString()} - ${new Date(group[0].endDate).toLocaleDateString()}`}
                      </TableCell>
                      <TableCell align="right">{formatMoney(group[0].principal)}</TableCell>
                      <TableCell align="right">{formatMoney(group[0].profit)}</TableCell>
                      <TableCell align="right">{formatRate(group[0].actualRate)}</TableCell>
                      <TableCell align="right">{group[0].dailyProfit.toFixed(2)}元</TableCell>
                      <TableCell align="center">
                        <Tooltip title="编辑">
                          <IconButton
                            size="small"
                            onClick={() => handleEditReverseCalculation(group[0])}
                          >
                            <EditIcon />
                          </IconButton>
                        </Tooltip>
                        <Tooltip title="删除">
                          <IconButton
                            size="small"
                            onClick={() => handleDeleteReverseCalculation(group[0].id)}
                          >
                            <DeleteIcon />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                    
                    {/* 其他记录 */}
                    {group.slice(1).map((calc) => (
                      <TableRow key={calc.id}>
                        <TableCell>
                          {`${new Date(calc.startDate).toLocaleDateString()} - ${new Date(calc.endDate).toLocaleDateString()}`}
                        </TableCell>
                        <TableCell align="right">{formatMoney(calc.principal)}</TableCell>
                        <TableCell align="right">{formatMoney(calc.profit)}</TableCell>
                        <TableCell align="right">{formatRate(calc.actualRate)}</TableCell>
                        <TableCell align="right">{calc.dailyProfit.toFixed(2)}元</TableCell>
                        <TableCell align="center">
                          <Tooltip title="编辑">
                            <IconButton
                              size="small"
                              onClick={() => handleEditReverseCalculation(calc)}
                            >
                              <EditIcon />
                            </IconButton>
                          </Tooltip>
                          <Tooltip title="删除">
                            <IconButton
                              size="small"
                              onClick={() => handleDeleteReverseCalculation(calc.id)}
                            >
                              <DeleteIcon />
                            </IconButton>
                          </Tooltip>
                        </TableCell>
                      </TableRow>
                    ))}
                    
                    {/* 合计行 */}
                    <TableRow sx={{ backgroundColor: 'action.hover' }}>
                      <TableCell>合计</TableCell>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                        {formatMoney(group.reduce((sum, calc) => sum + calc.principal, 0))}
                      </TableCell>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                        {formatMoney(group.reduce((sum, calc) => sum + calc.profit, 0))}
                      </TableCell>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                        {formatRate(
                          // 计算加权平均年化收益率
                          group.reduce((sum, calc) => sum + calc.actualRate * calc.principal, 0) /
                          group.reduce((sum, calc) => sum + calc.principal, 0)
                        )}
                      </TableCell>
                      <TableCell align="right" sx={{ fontWeight: 'bold' }}>
                        {(group.reduce((sum, calc) => sum + calc.dailyProfit * calc.principal / 10000, 0) /
                         group.reduce((sum, calc) => sum + calc.principal, 0) * 10000).toFixed(2)}元
                      </TableCell>
                      <TableCell></TableCell>
                    </TableRow>
                  </React.Fragment>
                ))}
              </TableBody>
            </Table>
          </TableContainer>
        </Box>
      ) : (
        <Box textAlign="center" mt={4}>
          <Typography color="textSecondary">
            点击"收益反算"按钮开始计算实际收益
          </Typography>
        </Box>
      )}
      </TabPanel>
      
      <TabPanel value={tabValue} index={2}>
        <PerformanceAnalysis 
          calculations={calculations} 
          reverseCalculations={reverseCalculations} 
        />
      </TabPanel>

      <Dialog
        open={openInvestForm}
        onClose={() => setOpenInvestForm(false)}
        maxWidth="md"
        fullWidth
      >
        <InvestmentForm
          products={products}
          initialData={editingInvestment}
          onSubmit={(plan) => calculateInvestment(plan, true)}
          onClose={() => {
            setOpenInvestForm(false);
            setEditingInvestment(null);
          }}
        />
      </Dialog>

      <Dialog
        open={openReverseForm}
        onClose={() => {
          setOpenReverseForm(false);
          setEditingReverse(null);
        }}
        maxWidth="sm"
        fullWidth
      >
        <ReverseCalculationForm
          products={products}
          initialData={editingReverse}
          onSubmit={handleReverseCalculation}
          onClose={() => {
            setOpenReverseForm(false);
            setEditingReverse(null);
          }}
        />
      </Dialog>
    </Box>
  );
};

export default CalculatorPage;